package org.lanplay.server.dao;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import org.lanplay.server.model.User;

import com.google.inject.Inject;
import com.google.inject.Provider;

public class UserDao implements Serializable {
	private static final long serialVersionUID = 1L;

	@Inject
	private Provider<EntityManager> emp;

	public void save(User user) {
		emp.get().persist(user);
	}

	public User getById(long id) {
		return emp.get().find(User.class, id);
	}

	public User getByKey(String key) {
		Query query = emp.get().createQuery(
				"SELECT u from User as u where u.key=:key");
		query.setParameter("key", key);
		try {
			return (User) query.getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}

	public User getByName(String name) {
		Query query = emp
				.get()
				.createQuery(
						"SELECT u from User as u where u.name=:name and name is not null");
		query.setParameter("name", name);
		try {
			return (User) query.getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	public List<User> getUserList() {
		return emp.get().createQuery("SELECT u from User as u").getResultList();
	}
}
